package com.ssm.wechat.controller;

import com.ssm.wechat.handler.WeChatMsgFactory;
import com.ssm.wechat.handler.WeChatMsgHandler;
import com.ssm.wechat.utils.MessageUtil;
import com.ssm.wechat.utils.SHA1;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

@RestController
@Log4j2
public class CallBackController {

    private static final String token = "ShiShuoMing";

    @Resource
    private WeChatMsgFactory weChatMsgFactory;

    /**
     * 回调消息校验
     * signature 与 sha1加密后的token、timestamp、nonce 进行对比，成功则返回echostr，成为开发者。
     * encrypt 采取明文存储，不需要密钥
     */
    @GetMapping("callback")
    public String callback(@RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("echostr") String echostr) {
        log.info("get验签请求参数：signature:{}，timestamp:{}，nonce:{}，echostr:{}",
                signature, timestamp, nonce, echostr);
        String shaStr = SHA1.getSHA1(token, timestamp, nonce, "");
        if (signature.equals(shaStr)) {
            return echostr;
        }
        return "unknown";
    }

    /**
     * 接收普通信息接口(接收消息、关注、取关等)：微信服务器向配置的URL地址发送POST请求，将xml数据包发送过来
     * @requestBody: 请求的消息体会放到requestBody里
     * @msg_signature: 开启加密模式时，post请求还会发送meg_signature消息用于验签，明文时不会发送
     */
    @PostMapping(value = "callback", produces = "application/xml;charset=UTF-8")
    public String callback(
            @RequestBody String requestBody,
                           @RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam(value = "meg_signature", required = false) String msgSignature) {
        log.info("接收到微信的请求：request:{}", requestBody);
        Map<String, String> msgMap = MessageUtil.parseXml(requestBody);
        String msgType = msgMap.get("MsgType");
        String event = msgMap.get("Event") == null ? null : msgMap.get("Event");
        log.info("msgType:{}, event:{}", msgType, event);
        //构建key(text || event.subscribe)
        String msgTypeKey = msgType +  (event == null ? "" : "." + event);
        WeChatMsgHandler weChatMsgHandler = weChatMsgFactory.getHandlerByMsgType(msgTypeKey);
        //关注 和 发消息 以外的事件返回unknown
        if(Objects.isNull(weChatMsgHandler)) {
            return "unknown"; //只有xml形式的数据，公众号才会显示，返回unknown，不会显示
        }
        String replayContent = weChatMsgHandler.dealMsg(msgMap);
        log.info("replayContent:{}", replayContent);
        return replayContent;
    }
}
